import os
import sys

from PySide6.QtWidgets import QFileDialog, QMessageBox, QWidget, QApplication

from .crypt_ui import Ui_Form
from .core import CryGz, blackwhite_image

AppName = "x01.FileProcess"


class CryptWidget(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.pushButton_SelectDirectory.clicked.connect(self.SelectDirectory)
        self.ui.pushButton_SelectFilename.clicked.connect(self.SelectKeyFilename)
        self.ui.pushButton_SelectDestFilename.clicked.connect(self.SelectDestFilename)
        self.ui.pushButton_Compress.clicked.connect(self.Compress)
        self.ui.pushButton_GenerateKey.clicked.connect(self.GenerateKey)
        self.ui.pushButton_BlackWhiteImage.clicked.connect(self.BlackWhiteImage)
        self.ui.pushButton_Encrypt.clicked.connect(self.Encrypt)
        self.ui.pushButton_Decrypt.clicked.connect(self.Decrypt)
        self.ui.pushButton_split.clicked.connect(self.Split)
        self.ui.pushButton_Combine.clicked.connect(self.Combine)
        self.ui.lineEdit_ExtName.setText(".md")
        self.crygz: CryGz = CryGz()
        self.filename = os.path.join(os.path.expanduser("~"),r"Desktop\temp")

        self.setWindowTitle(AppName)

    def SelectDirectory(self):
        directory = QFileDialog.getExistingDirectory(
            self,
            "Select Directory",
            os.path.dirname(self.filename),
        )
        if directory:
            self.ui.lineEdit_OrgDirectory.setText(directory)
            self.filename = os.path.join(directory, "temp")

    def SelectKeyFilename(self):
        filename, ext = QFileDialog.getOpenFileName(
            self,
            "OpenFile",
            os.path.dirname(self.filename),
            " All File (*)",
        )
        if filename:
            self.ui.lineEdit_KeyFilename.setText(filename)
            self.filename = filename

    def SelectDestFilename(self):
        filename, ext = QFileDialog.getOpenFileName(
            self,
            "OpenFile",
            os.path.dirname(self.filename),
            "Zip File (*.zip);;Crypt File(*.cry);; All File (*)",
        )
        if filename:
            self.ui.lineEdit_DestFilename.setText(filename)
            self.filename = filename

    def Compress(self):
        try:
            directory = self.ui.lineEdit_OrgDirectory.text()
            self.crygz.gztar(directory, fmt="zip")
            QMessageBox.about(self, AppName, "压缩成功！")
        except Exception as e:
            QMessageBox.about(self, AppName, f"Errors: {e}")

    def GenerateKey(self):
        try:
            directory = os.path.dirname(self.ui.lineEdit_KeyFilename.text())
            self.crygz.gen_keyiv(directory)
            QMessageBox.about(self, AppName, "生成密钥成功！")
        except Exception as e:
            QMessageBox.about(self, AppName, f"Errors: {e}")

    def Encrypt(self):
        try:
            filename = self.ui.lineEdit_DestFilename.text()
            keyfielname = self.ui.lineEdit_KeyFilename.text()
            title = self.windowTitle()
            self.setWindowTitle("正在加密，请等待...")
            self.crygz.encrypt_file(filename=filename, keyivfile=keyfielname)
            self.setWindowTitle(title)
            QMessageBox.about(self, AppName, "加密成功！")
        except Exception as e:
            QMessageBox.about(self, AppName, f"Errors: {e}")

    def Decrypt(self):
        try:
            filename = self.ui.lineEdit_DestFilename.text()
            keyfielname = self.ui.lineEdit_KeyFilename.text()
            title = self.windowTitle()
            self.setWindowTitle("正在解密，请等待...")
            self.crygz.decrypt_file(filename=filename, keyivfile=keyfielname)
            self.setWindowTitle(title)
            QMessageBox.about(self, AppName, "解密成功！")
        except Exception as e:
            QMessageBox.about(self, AppName, f"Errors: {e}")

    def Split(self):
        try:
            filename = self.ui.lineEdit_DestFilename.text()
            count = int(self.ui.lineEdit_SplitCount.text())
            title = self.windowTitle()
            self.setWindowTitle("正在分割，请等待...")
            self.crygz.split_file(filename=filename, count=count)
            self.setWindowTitle(title)
            QMessageBox.about(self, AppName, "分割成功！")
        except Exception as e:
            QMessageBox.about(self, AppName, f"Errors: {e}")

    def Combine(self):
        try:
            dirname = self.ui.lineEdit_OrgDirectory.text().strip()
            ext = self.ui.lineEdit_ExtName.text().strip()
            title = self.windowTitle()
            self.setWindowTitle("正在合并，请等待...")
            self.crygz.combine_files(dirname, ext)
            self.setWindowTitle(title)
            QMessageBox.about(self, AppName, "合并成功！")
        except Exception as e:
            QMessageBox.about(self, AppName, f"Errors: {e}")

    def BlackWhiteImage(self):
        ''' 借用一下界面'''
        try:
            filename = self.ui.lineEdit_KeyFilename.text().strip()
            threshold = int(self.ui.lineEdit_SplitCount.text().strip())
            if threshold < 20 or threshold > 250: 
                threshold=160
            blackwhite_image(filename, threshold)
            QMessageBox.about(self, AppName, "黑白图像处理成功！")
        except Exception as e:
            QMessageBox.about(self, AppName, f"Errors: {e}")
        



def run():
    app = QApplication(sys.argv)
    win = CryptWidget()
    win.move(100, 50)
    win.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    run()
